package sp.whereru;

import java.util.ArrayList;
import XMLread.BuildingCSV;
import XMLread.Space;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddCourseActivity extends FragmentActivity 
implements DayPickerDialog.DayPickerDialogListener {

	public static final int NUM_DAYS = 6;

	final FragmentManager fm = getSupportFragmentManager();
	CourseDbAdapter courseDbAdapter;
	MapDbAdapter mapDbAdapter;
	TimePickerButton startTimePicker;
	TimePickerButton endTimePicker;
	Spinner buildingSpinner;
	Spinner roomSpinner;
	Button daysButton;
	Course courseToEdit;
	boolean isEditing;
	long courseId;

	ArrayList<BuildingCSV> buildings;
	SparseArray<ArrayList<Space>> spaces;

	boolean[] daysPicked = new boolean[NUM_DAYS];
	boolean[] lastDaysPicked = new boolean[NUM_DAYS];

	String courseDays = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_course);

		isEditing = false;
		
		courseDbAdapter = new CourseDbAdapter(this);
		courseDbAdapter.open();
		mapDbAdapter = new MapDbAdapter(this);
		mapDbAdapter.open();

		Button startTimeButton = (Button) findViewById(R.id.button_start_time);
		Button endTimeButton = (Button) findViewById(R.id.button_end_time);
		daysButton = (Button) findViewById(R.id.button_days);

		startTimePicker = new TimePickerButton(startTimeButton, this);
		endTimePicker = new TimePickerButton(endTimeButton, this);

		buildingSpinner = (Spinner) findViewById(R.id.buildings_spinner);
		roomSpinner = (Spinner) findViewById(R.id.room_spinner);
		buildings = ( (MyApplication) this.getApplication() ).getBuildings();
		spaces = ( (MyApplication) this.getApplication() ).getSpaces();
		setBuildingSpinner();

		daysButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDayPickerDialog();
			}
		});


		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		// check to see if user is editing a course or adding new one
		if(extras == null) { }
		else { // user is editing a course, insert current values into views
			isEditing = true;
			courseId = extras.getLong(CourseScheduleActivity.EXTRA_COURSE_ID);
			courseToEdit = courseDbAdapter.returnCourse(courseId);
			TextView tvTitle = (TextView) findViewById(R.id.text_add_course);
			EditText etCourseName = (EditText) findViewById(R.id.et_course_name);
			Button buttonDays = (Button) findViewById(R.id.button_days);
			Button buttonSubmit = (Button) findViewById(R.id.button_submit_course);

			tvTitle.setText("Edit Course");
			etCourseName.setText(courseToEdit.getName(), TextView.BufferType.EDITABLE);

			String buildingName = courseToEdit.getBuilding();
			for(int i = 0; i < buildingSpinner.getCount(); i++) {
				if(buildingName.equals(buildingSpinner.getItemAtPosition(i).toString())) {
					buildingSpinner.setSelection(i, true);
				}
			}				

			updateRoomSpinner(buildingSpinner, roomSpinner);

			String roomNum = courseToEdit.getRoomNum();
			for(int i = 0; i < roomSpinner.getCount(); i++) {
				if(roomNum.equals(roomSpinner.getItemAtPosition(i).toString())) {
					roomSpinner.setSelection(i, true);
				}
			}

			startTimePicker.setTime(courseToEdit.getStartTime().getHours(), 
					courseToEdit.getStartTime().getMinutes());
			endTimePicker.setTime(courseToEdit.getEndTime().getHours(), 
					courseToEdit.getEndTime().getMinutes());

			courseDays = courseToEdit.getDays();
			buttonDays.setText(courseDays);
			daysStringToBoolean(courseDays);
			for(int i=0; i < NUM_DAYS; i++) 
				lastDaysPicked[i] = daysPicked[i];

			buttonSubmit.setText("Submit Changes");        	
		}
	}

	/**
	 * Called when the user presses the back button
	 * Closes the database and finishes the activity
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		courseDbAdapter.close();
		finish();
	}
	
	public void onDestroy() {
		super.onDestroy();
		mapDbAdapter.close();
		courseDbAdapter.close();
	}



	private void setBuildingSpinner() {
		Spinner buildingSpinner = (Spinner) findViewById(R.id.buildings_spinner);

		// Create an ArrayAdapter using all the buildingIds from our buildings that are parsed		
		ArrayList<String> buildingNames = mapDbAdapter.getBuildingNames(true);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, buildingNames);
		// Specify the layout to use when the list of choices appears
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		buildingSpinner.setAdapter(adapter);
		buildingSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				updateRoomSpinner((Spinner) parent, roomSpinner);
			}
			public void onNothingSelected(AdapterView<?> parent) { }
		});
	}

	private void updateRoomSpinner(Spinner buildingSpinner, Spinner roomSpinner) {
		// get list of classrooms based on the current building
		ArrayList<String> sClassrooms = mapDbAdapter.getRooms(buildingSpinner.getSelectedItem().toString());
		ArrayAdapter<String> roomAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sClassrooms);
		roomAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		roomSpinner.setAdapter(roomAdapter);
	}


	/**
	 * Shows the day picker dialog
	 */
	public void showDayPickerDialog() {
		// Create an instance of the dialog fragment and show it
		DialogFragment dialog = DayPickerDialog.newInstance(this, daysPicked);
		dialog.show(getSupportFragmentManager(), "DayPickerDialog");
	}

	/**
	 * Method is called when the user clicks "OK" on the day picker
	 * This sets the courseDays string according to the users selection
	 */
	public void onDayPickerDialogPositiveClick(DialogFragment dialog) {
		// User touched the dialog's positive button    	
		courseDays = "";
		for(int i=0; i < NUM_DAYS; i++) {
			if(daysPicked[i] == true) {
				switch(i) {
				case 0:  
					courseDays += "M ";
					break;
				case 1: 
					courseDays += "T ";
					break;
				case 2: 
					courseDays += "W ";
					break;
				case 3: 
					courseDays += "R ";
					break;
				case 4: 
					courseDays += "F ";
					break;
				case 5: 
					courseDays += "S ";
					break;
				}
			}
		}
		boolean isSelected = false;
		for(int i=0; i < NUM_DAYS; i++) {
			lastDaysPicked[i] = daysPicked[i];
			if(daysPicked[i] == true)
				isSelected = true;
		}
		if(isSelected) {
			daysButton.setText(courseDays);
		}
		else
			daysButton.setText(R.string.button_noDays);
	}

	/**
	 *	Method is called when the user clicks cancel on the day picker
	 */
	public void onDayPickerDialogNegativeClick(DialogFragment dialog) {
		// User touched the dialog's negative button
		for(int i=0; i < NUM_DAYS; i++)
			daysPicked[i] = lastDaysPicked[i];
	}

	/**
	 * If the user checks a day in the list
	 */
	public void onDayPickerMultiChoiceItemClick(DialogFragment dialog, 
			DialogInterface iDialog, int which, boolean isChecked) {
		// User touched the positive button
	}

	/**
	 * Adds a given course to the users schedule
	 */
	public void addCourseToSchedule(View view){
		Toast toast;

		EditText courseName = (EditText) findViewById(R.id.et_course_name);


		if(courseName.getText().toString().trim().equals("")) {
			toast = Toast.makeText(getApplicationContext(), 
					"You must enter a course name", Toast.LENGTH_SHORT); 
			toast.show();
		}
		else if(!startTimePicker.isSet()) {
			toast = Toast.makeText(getApplicationContext(), 
					"You must enter a start time", Toast.LENGTH_SHORT);
			toast.show();
		}
		else if(!endTimePicker.isSet()) {
			toast = Toast.makeText(getApplicationContext(), 
					"You must enter an end time", Toast.LENGTH_SHORT);
			toast.show();
		}
		else if(courseDays.equals("")) {
			toast = Toast.makeText(getApplicationContext(), 
					"You must select at least one day", Toast.LENGTH_SHORT);
			toast.show();
		}
		// entries are correct, add the course to the database
		else {
			Spinner buildingSpinner = (Spinner) findViewById(R.id.buildings_spinner);
			Spinner roomSpinner = (Spinner) findViewById(R.id.room_spinner);
			String building = buildingSpinner.getSelectedItem().toString();
			String room = roomSpinner.getSelectedItem().toString();

			if(isEditing) {
				courseDbAdapter.updateCourse(courseId, courseName.getText().toString().trim(), building, room, 
						startTimePicker.getSimpleTime().getTotalTime(), 
						endTimePicker.getSimpleTime().getTotalTime(), 
						courseDays.trim(), courseToEdit.getAlarmIsSet(), courseToEdit.getAlarmDelay());
				CourseAlarmManager alarmManager = new CourseAlarmManager(this);
				alarmManager.setAlarm(courseDbAdapter.returnCourse(courseId));
			}
			else {
				courseDbAdapter.addCourse(courseName.getText().toString().trim(), building, room, 
						startTimePicker.getSimpleTime().getTotalTime(), 
						endTimePicker.getSimpleTime().getTotalTime(), 
						courseDays.trim(), 0, 0);
			}
			finish();	// finish the activity
		}
	}

	/**
	 * Sets the boolean array daysPicked according to the string 
	 * representation of days
	 * @param days	the string representation of days
	 */
	private void daysStringToBoolean(String days) {
		String[] array = days.split(" ");
		for(int i = 0; i<array.length; i++) {
			if(array[i].equals("M"))
				daysPicked[0] = true;
			else if(array[i].equals("T"))
				daysPicked[1] = true;
			else if(array[i].equals("W"))
				daysPicked[2] = true;
			else if(array[i].equals("R"))
				daysPicked[3] = true;
			else if(array[i].equals("F"))
				daysPicked[4] = true;
			else if(array[i].equals("S"))
				daysPicked[5] = true;			
		}
	}
}